package com.ruoyi.web.controller.wx.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.HttpClientUtil;
import com.ruoyi.system.domain.HomeUser;
import com.ruoyi.system.domain.vo.WxLoginRequest;
import com.ruoyi.system.mapper.HomeUserMapper;
import com.ruoyi.web.controller.wx.service.IWxLoginService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.framework.web.service.TokenService;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WxLoginServiceImpl implements IWxLoginService {

    @Value("${wechat.appid}")
    private String AppId;
    @Value("${wechat.secret}")
    private String secret;

    @Autowired
    private HomeUserMapper homeUserMapper;

    @Autowired
    private TokenService tokenService;


    @Override
    public Map<String, Object> getPhoneNumber(String code) {
        String wxAccessToken = getWxAccessToken();
        String response = HttpUtil.post("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+wxAccessToken, "{\n" +
                "\t\"code\": \""+code+"\"\n" +
                "}");
        Map<String,Object> map = new HashMap<>();
        cn.hutool.json.JSONObject responseJson = JSONUtil.parseObj(response);
        System.out.println(response);
        String errcode = responseJson.get("errcode").toString();
        String errmsg = responseJson.get("errmsg").toString();
        System.out.println(errcode);
        System.out.println(errmsg);
        String phoneInfo = responseJson.get("phone_info").toString();
        cn.hutool.json.JSONObject responseJson2 = JSONUtil.parseObj(phoneInfo);
        String purePhoneNumber = responseJson2.get("purePhoneNumber").toString();
        String phoneNumber = responseJson2.get("phoneNumber").toString();

        map.put("errcode",errcode);
        map.put("errmsg",errmsg);
        map.put("purePhoneNumber",purePhoneNumber);
        map.put("errmsg",errmsg);
        map.put("phoneNumber",phoneNumber);
        return map;
    }

    @Override
    public Map<String, Object> userLogin(WxLoginRequest wxLoginRequest) {
        String params = "?appid=" + AppId + "&secret=" + secret + "&js_code=" + wxLoginRequest.getCode() + "&grant_type=authorization_code";
        String url = "https://api.weixin.qq.com/sns/jscode2session" + params;
        String response= HttpClientUtil.doGet(url);

        JSONObject responseJson = JSONObject.parseObject(response);
        System.out.println(responseJson);
        String sessionKey = (String) responseJson.get("session_key");
        System.out.println(sessionKey);
        String openId = (String) responseJson.get("openid");
        System.out.println(openId);
        String unionid = (String) responseJson.get("unionid");
        System.out.println("----unionid-----"+unionid);
        QueryWrapper<HomeUser> homeUserQueryWrapper=new QueryWrapper<>();
        homeUserQueryWrapper.lambda().eq(HomeUser::getOpenId,openId);
        HomeUser homeUser = homeUserMapper.selectOne(homeUserQueryWrapper);
        LoginUser loginUser = new LoginUser();
        Map<String, Object> map = new HashMap<>();
        if (ObjectUtils.isNotEmpty(homeUser)){
            loginUser.setUserId(homeUser.getId());
            loginUser.setUser(new SysUser());
            String token = tokenService.createToken(loginUser);
            map.put("token","Bearer "+token);
            map.put("user",homeUser);
        }else {
            if (ObjectUtils.isNotEmpty(openId)) {
                homeUser = new HomeUser();
                homeUser.setHeadPortrait(wxLoginRequest.getHeadPortrait());
                homeUser.setOpenId(openId);
                homeUser.setPhoneNumber(wxLoginRequest.getPhoneNumber());
                homeUser.setCreateTime(new Date());
                homeUser.setUserName(wxLoginRequest.getNickName());
                homeUser.setIsSale(0);
                homeUserMapper.insert(homeUser);
                loginUser.setUserId(homeUser.getId());
                loginUser.setUser(new SysUser());
                String token = tokenService.createToken(loginUser);
                map.put("token", "Bearer " + token);
                map.put("user", homeUser);
            }
        }
        return map;
    }


    public String getWxAccessToken() {
        HashMap<String, Object> parameters = new HashMap(16);
        parameters.put("grant_type", "client_credential");
        parameters.put("appid", AppId);
        parameters.put("secret", secret);
        // 高德获取地理信息
        String response = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token", parameters);
        cn.hutool.json.JSONObject responseJson = JSONUtil.parseObj(response);
        String accessToken = responseJson.get("access_token").toString();
        return accessToken;
    }


}
